#!/bin/bash

run_user=`whoami`

if [ 'X'$run_user != 'X''root' ]
then
    echo 'Error! should run me with root...'
    exit 1
fi

cnt=`ps aux | grep mysql | grep -v $0 | grep -v 'grep' | wc -l`
if [ $cnt -gt 0 ]
then
    echo "ERROR! mysql may be running or installing, exit..."
    exit 10
fi

# recommend: don't change it
INSTALL_HOME="/usr/local/mysql"
if [ -d ${INSTALL_HOME} ]
then
    echo "ERROR! mysql home:${INSTALL_HOME} exists, exit..."
    exit 10
fi

# mysql data path, can change to your another disk if needed
MYSQL_DATA_PATH="${INSTALL_HOME}/data"
if [ -d ${MYSQL_DATA_PATH} ]
then
    echo "ERROR! data dir:${MYSQL_DATA_PATH} exists, exit..."
    exit 10
fi

# absolute path of mysql tarball used
# like: https://cdn.mysql.com//Downloads/MySQL-8.0/mysql-8.0.30-linux-glibc2.12-x86_64.tar.xz
# like: https://cdn.mysql.com/archives/mysql-5.7/mysql-5.7.39-linux-glibc2.12-x86_64.tar.gz
# download tarball and upload to your machine then use this script to install it
# all of mysql-5.7 and mysql-8 is supported
TARBALL_PATH=''

# absolute path of mysql configuration file used, defaults to '/tmp/mysql_env.config'
MYSQL_CONF_PATH=''

usage() { 
  echo -e "
Usage:
  $0 -f ARCHIVE_TARBARR_PATH [-c CONFIGURATION_PATH]
Common options:
  -f,  file, absolute path of archive tarball. Without -f options will download tarball from Internet
  -c,  conf, absolute path of configuration file, default to "'`/tmp/mysql_env.config`'"
" 1>&2; exit 1;
}

while getopts ":f:c:v:" o; do
    case "${o}" in
        f)
            v=${OPTARG}
            if [ 'X'$v == 'X' ]
            then
              usage
            else
              TARBALL_PATH=${OPTARG}
            fi
            ;;
        c)
            v=${OPTARG}
            if [ 'X'$v == 'X' ]
            then
              usage
            else
              MYSQL_CONF_PATH=${OPTARG}
            fi
            ;;
        *)
            usage
            ;;
    esac
done
shift $((OPTIND-1))


if [ 'X'${TARBALL_PATH} == 'X' ]
then
    echo "ERROR! not give mysql tarball path, exit..."
    usage
    exit 11
fi
if [ ! -f ${TARBALL_PATH} ]
then
    echo "ERROR! mysql tarball:${TARBALL_PATH} not found, exit..."
    exit 11
fi


if [ 'X'${MYSQL_CONF_PATH} == 'X' ]
then
    MYSQL_CONF_PATH='/tmp/mysql_env.config'
    echo "not give mysql configuration file absolute path, will use default path: ${MYSQL_CONF_PATH}"
fi

is_centos=`awk -F '=' '/PRETTY_NAME/ { print $2 }' /etc/os-release | grep -i centos | wc -l`
is_ubuntu=`awk -F '=' '/PRETTY_NAME/ { print $2 }' /etc/os-release | grep -i ubuntu | wc -l`

remove_mysql_centos(){
    # stop mysql process
    systemctl stop mysql
    chkconfig mysql off
    chkconfig --del mysql
    rm -rf /etc/init.d/mysql
    
    # del previous mysql user
    userdel mysql
    groupdel mysql
    
    cd /
    # remove mariadb* and mysql* with yum
    yum remove mariadb* -y
    yum remove mysql* -y

    # remove previous mysql conf
    # rm -rf /etc/my.cnf
    # rm -rf /etc/mysql
}

install_libs_centos(){
    yum update -y
    yum install libaio -y
    yum install ncurses-compat-libs -y
    # install dos2unix to process some text files
    yum install dos2unix -y
}

remove_mysql_ubuntu(){
    # stop mysql process
    systemctl stop mysql
    update-rc.d remove mysql
    rm -rf /etc/init.d/mysql
    
    # del previous mysql user
    userdel mysql
    groupdel mysql
    
    cd /
    # remove mariadb* and mysql* with yum
    apt-get remove mariadb* -y
    apt-get remove mysql* -y

    # remove previous mysql conf
    # rm -rf /etc/my.cnf
    # rm -rf /etc/mysql
}

install_libs_ubuntu(){
    apt-get update -y
    apt-get install libaio1 -y
    # install dos2unix to process some text files
    apt-get install dos2unix -y
}

if [ $is_centos -gt 0 ]
then
    # stop and remove mysql
    remove_mysql_centos
    # install some libs
    install_libs_centos
fi

if [ $is_ubuntu -gt 0 ]
then
    # stop and remove mysql
    remove_mysql_ubuntu
    # install some libs
    install_libs_ubuntu
fi

# add mysql user and group
groupadd mysql
useradd -g mysql mysql

echo 'prepare install mysql, please wait...'

mkdir -p ${INSTALL_HOME}
suffix=`echo ${TARBALL_PATH} | awk -F'.' '{print $NF}'`
if [ $suffix == 'xz' ]
then
    xz -dc ${TARBALL_PATH} | tar -x  -C ${INSTALL_HOME} --strip-components 1
fi
if [ $suffix == 'gz' ]
then
    tar -xzf ${TARBALL_PATH} -C ${INSTALL_HOME} --strip-components 1
fi

cd ${INSTALL_HOME}

# create files/dirs
mkdir mysql-files

touch my.cnf

# load mysql config from custom configs files
# clear previous env
export mysql_port=
export mysql_root_password=

if [ -f ${MYSQL_CONF_PATH} ]
then
    dos2unix ${MYSQL_CONF_PATH}
    . ${MYSQL_CONF_PATH}
else
    echo "${MYSQL_CONF_PATH} not found, will use mysql default port and password"
fi

if [ 'X'${mysql_port} == 'X' ]
then
    mysql_port=3306
    echo "use mysql default port: ${mysql_port}"
fi

if [ 'X'${mysql_root_password} == 'X' ]
then
    mysql_root_password='root.123'
    echo "use mysql default password: ${mysql_root_password}"
fi


echo "
[mysqld] 
# 事务隔离级别
transaction_isolation=READ-COMMITTED
# 不区分大小写，linux下1表示大小写不敏感
lower_case_table_names=1

skip-name-resolve

# 设置mysql-server监听端口
port=${mysql_port}

# 设置mysql数据库的数据的存放目录
datadir=${MYSQL_DATA_PATH}

# 允许最大连接数
max_connections=65536
# 允许连接失败的次数。这是为了防止有人从该主机试图攻击数据库系统
max_connect_errors=10
# 服务端使用的字符集默认为UTF8
character-set-server=UTF8MB4
# 创建新表时将使用的默认存储引擎
default-storage-engine=INNODB

pid-file=/var/lib/mysql/mysqld.pid

[client]
# 设置mysql客户端默认字符集
default-character-set=UTF8MB4

" > my.cnf

dos2unix ${INSTALL_HOME}/my.cnf

echo "mysql configs added to: ${INSTALL_HOME}/my.cnf"

cd ${INSTALL_HOME}

# chg rwx perms
cd ..
chown -R mysql:mysql ${INSTALL_HOME}
chmod -R 755 ${INSTALL_HOME}

cd ${INSTALL_HOME}
chown mysql:mysql mysql-files
chmod 750 mysql-files

# create mysql data dir
if [ ! -d ${MYSQL_DATA_PATH} ]
then
    mkdir -p ${MYSQL_DATA_PATH}
fi
chown -R mysql:mysql ${MYSQL_DATA_PATH}
chmod -R 700 ${MYSQL_DATA_PATH}

# create /var/lib/mysql for pid file
if [ ! -d /var/lib/mysql ]
then
    mkdir -p /var/lib/mysql
fi
chown -R mysql:mysql /var/lib/mysql

# init mysql-server
echo 'install mysql completed, do initialize now...'

rm -rf /var/lib/mysql/mysqld.pid

cd ${INSTALL_HOME}
# add lower_case_table_names option, as config file 
bin/mysqld --initialize-insecure --user=mysql --basedir=${INSTALL_HOME} --datadir=${MYSQL_DATA_PATH} --lower_case_table_names=1 

cd ${INSTALL_HOME}/support-files/
./mysql.server start

# wait for mysql-server ready for connections
start_sec=`date +%s`
wait_sec=10

if [ ! -e /var/lib/mysql/mysqld.pid ]
then
    cur_sec=`date +%s`
    delta=`echo $cur_sec - $start_sec | bc`
    if [ $delta -gt $wait_sec ]
    then
        echo "mysql-server may in launching for a too long time or throw error, check logs in ${MYSQL_DATA_PATH}"
        exit 11
    else
        echo "mysql-server in launching, wait..."
        sleep 1
    fi
fi

# sleep more time to wait launching completed and cerating mysql.sock
sleep 5

cd ${INSTALL_HOME}
# mysql -u $user -p$passsword -Bse "command1;command2;....;commandn"
# alter root user to change default password
bin/mysql -uroot -hlocalhost -P${mysql_port} --skip-password -Bse "use mysql; ALTER USER 'root'@'localhost' IDENTIFIED BY '${mysql_root_password}';"
# add root@% to connect from everywhere
bin/mysql -uroot -hlocalhost -P${mysql_port} -p${mysql_root_password} -Bse "use mysql; CREATE USER 'root'@'%' IDENTIFIED BY '${mysql_root_password}';"
bin/mysql -uroot -hlocalhost -P${mysql_port} -p${mysql_root_password} -Bse "use mysql; grant all privileges  on *.* to 'root'@'%';"

sleep 5
# stop mysql-server after initialized
cd ${INSTALL_HOME}/support-files/
./mysql.server stop
sleep 5

start_on_boot_centos(){
    # add mysql to service use chkconfig
    cd ${INSTALL_HOME}/support-files/
    ln -s ${INSTALL_HOME}/support-files/mysql.server /etc/init.d/mysql
    chkconfig --add mysql
    chkconfig mysql on
}

start_on_boot_ubuntu(){
    # add mysql to service use update-rc.d
    cd ${INSTALL_HOME}/support-files/
    ln -s ${INSTALL_HOME}/support-files/mysql.server /etc/init.d/mysql
    update-rc.d mysql defaults
}

if [ $is_centos -gt 0 ]
then
    # start mysql on boot
    start_on_boot_centos
fi

if [ $is_ubuntu -gt 0 ]
then
    # start mysql on boot
    start_on_boot_ubuntu
fi

systemctl daemon-reload


echo "install and initialize mysql completed, will start mysql-server now"
sleep 5

systemctl start mysql

echo "mysql start and will automatically start on boot, use 'systemctl status mysql' to check"